{% extends "base.html" %}

{% set current_menu = 'project' %}
{% set current_page = 'gantt_chart' %}

{% block title %}甘特图 - 项目管理系统{% endblock %}

{% block page_title %}{% endblock %}
{% block page_subtitle %}{% endblock %}

{% block extra_css %}
<link rel="stylesheet" href="https://cdn.dhtmlx.com/gantt/edge/dhtmlxgantt.css">
<style>
    html, body {
        height: 100%;
        margin: 0;
        padding: 0;
        overflow: hidden;
    }
    .gantt_container {
        height: calc(100vh - 230px);
        width: 100%;
        min-height: 400px;
        border: 1px solid #ddd;
        background-color: #f9f9f9;
        overflow: hidden;
        box-sizing: border-box;
    }
    /* 自定义甘特图任务颜色 */
    .gantt_task_complete {
        background-color: #4CAF50 !important;
        border-color: #388E3C !important;
    }
    .gantt_task_in_progress {
        background-color: #2196F3 !important;
        border-color: #1976D2 !important;
    }
    .gantt_task_overdue {
        background-color: #F44336 !important;
        border-color: #D32F2F !important;
    }
    .gantt_task_not_started {
        background-color: #9E9E9E !important;
        border-color: #757575 !important;
    }
    /* 确保甘特图网格固定不滚动 */
    .gantt_container .gantt_grid {
        width: 300px !important;
        min-width: 300px !important;
        max-width: 300px !important;
        overflow: hidden !important;
    }
    /* 确保甘特图时间线可以滚动 */
    .gantt_container .gantt_timeline {
        width: auto !important;
        min-width: 600px;
        overflow-x: auto !important;
    }
    /* 隐藏网格区域的滚动条 */
    .gantt_container .gantt_grid .gantt_hor_scroll {
        display: none !important;
        height: 0 !important;
    }
    .gantt_container .gantt_grid .gantt_ver_scroll {
        display: none !important;
        width: 0 !important;
    }
    /* 确保时间线区域显示水平滚动条 */
    .gantt_container .gantt_timeline .gantt_hor_scroll {
        display: block !important;
        height: 15px !important;
    }
    /* 隐藏网格区域的所有滚动条相关元素 */
    .gantt_container .gantt_grid_scale {
        overflow: hidden !important;
    }
    .gantt_container .gantt_task_cell {
        overflow: hidden !important;
    }
    .gantt_container .gantt_task_bg {
        overflow: hidden !important;
    }
    .gantt_container .gantt_grid_data {
        overflow: hidden !important;
    }
</style>
{% endblock %}

{% block extra_js %}
{{ super() }}
<script src="https://cdn.dhtmlx.com/gantt/edge/dhtmlxgantt.js"></script>
<script>
    // 初始化甘特图
    function initGantt() {
        console.log("初始化甘特图...");
        
        // 检查gantt对象是否可用
        if (typeof gantt === 'undefined') {
            console.error("gantt对象未定义，请确保dhtmlxgantt.js已正确加载");
            return;
        }
        
        console.log("gantt对象已定义，开始配置甘特图");
        
        try {
            // 基本配置
            gantt.config.date_format = "%Y-%m-%d";
            gantt.config.xml_date = "%Y-%m-%d";
            gantt.config.scale_height = 50;
            gantt.config.add_column = false;
            gantt.config.autosize = "y";
            gantt.config.details_on_create = true;
            gantt.config.details_on_dblclick = true;
            
            // 禁用工作时间校正和日期拖拽舍入
            gantt.config.correct_work_time = false;
            gantt.config.round_dnd_dates = false;
            
            // 配置任务渲染
            gantt.config.task_height = 30;
            gantt.config.row_height = 40;
            
            // 配置日期显示格式（使用新版scale配置）
            gantt.config.scales = [
                {unit: "month", step: 1, format: "%Y年%m月"},
                {unit: "day", step: 1, format: "%Y-%m-%d"}
            ];
            
            // 配置列日期显示格式
            gantt.config.columns = [
                {name: "text", label: "任务名称", width: 200, tree: true},
                {name: "start_date", label: "开始日期", width: 100, align: "center", template: function(obj) {
                    if (obj.start_date) {
                        const date = gantt.date.parseDate(obj.start_date, gantt.config.date_format);
                        return gantt.date.date_to_str("%Y-%m-%d")(date);
                    }
                    return "";
                }},
                {name: "duration", label: "持续时间", width: 60, align: "center"},
                {name: "add", label: "", width: 40}
            ];
            
            // 添加中文本地化配置
            gantt.locale = {
                date: {
                    month_full: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
                    month_short: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
                    day_full: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
                    day_short: ["日", "一", "二", "三", "四", "五", "六"]
                },
                labels: {
                    new_task: "新任务",
                    icon_save: "保存",
                    icon_cancel: "取消",
                    icon_delete: "删除",
                    icon_details: "详情",
                    icon_edit: "编辑",
                    icon_add: "添加",
                    wdg_confirm: "确认",
                    wdg_cancel: "取消",
                    wdg_apply: "应用",
                    wdg_today: "今天",
                    wdg_tomorrow: "明天",
                    wdg_yesterday: "昨天",
                    wdg_hour: "小时",
                    wdg_minute: "分钟",
                    wdg_year: "年",
                    wdg_month: "月",
                    wdg_day: "日",
                    wdg_week: "周",
                    wdg_time: "时间",
                    wdg_period: "周期",
                    wdg_repeats: "重复",
                    wdg_every: "每个",
                    wdg_first: "第一个",
                    wdg_second: "第二个",
                    wdg_third: "第三个",
                    wdg_fourth: "第四个",
                    wdg_last: "最后一个",
                    wdg_workday: "工作日",
                    wdg_weekend: "周末",
                    wdg_start: "开始",
                    wdg_end: "结束",
                    wdg_after: "之后",
                    wdg_before: "之前",
                    wdg_ok: "确定",
                    wdg_close: "关闭",
                    wdg_yes: "是",
                    wdg_no: "否",
                    confirm_closing: "您的更改将会丢失，确定要关闭吗？",
                    confirm_deleting: "确定要删除吗？",
                    section_description: "描述",
                    section_time: "时间范围",
                    section_type: "类型",
                    column_text: "任务名称",
                    column_start_date: "开始日期",
                    column_duration: "持续时间",
                    column_add: "",
                    link: "链接",
                    confirm_link_deleting: "将被删除",
                    error_loading: "加载数据失败",
                    invalid_link: "无效的链接",
                    invalid_date: "无效的日期",
                    invalid_parent: "无效的父任务",
                    circular_reference: "循环引用",
                    gantt_error_task: "任务错误",
                    gantt_error_link: "链接错误",
                    gantt_error_resource: "资源错误",
                    gantt_error_constraint: "约束错误",
                    gantt_error_unknown: "未知错误"
                }
            };
            
            // 配置甘特图布局
            gantt.config.layout = {
                css: "gantt_container",
                cols: [
                    {
                        width: 300,
                        rows: [
                            {view: "grid", scrollX: "gridScroll", scrollY: "scrollVer"},
                            {view: "scrollbar", id: "gridScroll", group: "horizontal"}
                        ]
                    },
                    {resizer: true, width: 1},
                    {
                        rows: [
                            {view: "timeline", scrollX: "scrollHor", scrollY: "scrollVer"},
                            {view: "scrollbar", id: "scrollHor", group: "horizontal"}
                        ]
                    },
                    {view: "scrollbar", id: "scrollVer", group: "vertical"}
                ]
            };
            
            // 配置滚动条显示
            gantt.config.show_links = true;
            gantt.config.show_grid = true;
            
            // 自定义任务颜色
            gantt.templates.task_class = function(start, end, task) {
                if (task.status === 'completed') {
                    return "gantt_task_complete";
                } else if (task.status === 'in_progress') {
                    return "gantt_task_in_progress";
                } else if (task.status === 'overdue') {
                    return "gantt_task_overdue";
                } else {
                    return "gantt_task_not_started";
                }
            };
            
            // 自定义任务工具提示
            gantt.templates.tooltip_text = function(start, end, task) {
                return "<b>任务:</b> " + task.text + "<br/><b>负责人:</b> " + (task.assignee || "未分配") + "<br/><b>开始日期:</b> " + gantt.templates.date_grid(start, task) + "<br/><b>结束日期:</b> " + gantt.templates.date_grid(end, task);
            };
            
            console.log("甘特图配置完成");
            
            // 检查容器尺寸
            var ganttContainer = document.getElementById("gantt_here");
            if (!ganttContainer) {
                console.error("甘特图容器不存在");
                return;
            }
            
            // 检查容器是否已渲染
            if (ganttContainer.offsetWidth === 0) {
                console.warn("甘特图容器尚未渲染，可能存在样式问题");
                // 尝试设置默认尺寸
                ganttContainer.style.width = "100%";
                ganttContainer.style.height = "600px";
            }
            
            console.log("甘特图容器尺寸:", {
                width: ganttContainer.offsetWidth,
                height: ganttContainer.offsetHeight
            });
            
            // 初始化甘特图
            gantt.init("gantt_here");
            
            console.log("甘特图初始化完成");
            
            // 返回成功状态
            return true;
        } catch (e) {
            console.error("初始化甘特图失败:", e);
            return false;
        }
    }
    
    // 加载项目数据
    function loadProject() {
        var projectId = document.getElementById("project_select").value;
        if (!projectId) {
            console.log("未选择项目");
            return;
        }
        
        console.log("加载项目数据，项目ID:", projectId);
        
        // 隐藏空状态提示
        var emptyState = document.getElementById("empty-state");
        if (emptyState) {
            emptyState.style.display = "none";
        }
        
        // 显示加载状态
        var loadingElement = document.createElement("div");
        loadingElement.id = "gantt-loading";
        loadingElement.style.position = "absolute";
        loadingElement.style.top = "50%";
        loadingElement.style.left = "50%";
        loadingElement.style.transform = "translate(-50%, -50%)";
        loadingElement.style.padding = "20px";
        loadingElement.style.background = "rgba(255, 255, 255, 0.8)";
        loadingElement.style.borderRadius = "5px";
        loadingElement.style.boxShadow = "0 0 10px rgba(0, 0, 0, 0.2)";
        loadingElement.style.zIndex = "1000";
        loadingElement.innerHTML = "正在加载甘特图数据...";
        
        var container = document.getElementById("gantt_here");
        if (container) {
            container.appendChild(loadingElement);
        }
        
        // 获取项目数据
        fetch("/gantt/data/" + projectId)
            .then(response => {
                console.log("API响应状态:", response.status);
                if (!response.ok) {
                    throw new Error('Network response was not ok: ' + response.status);
                }
                return response.json();
            })
            .then(data => {
                console.log("API返回数据:", data);
                
                // 移除加载状态
                var loadingElement = document.getElementById("gantt-loading");
                if (loadingElement) {
                    loadingElement.remove();
                }
                
                // 检查gantt对象是否可用
                if (typeof gantt === 'undefined') {
                    console.error("gantt对象未定义，无法加载数据");
                    return;
                }
                
                try {
                    // 检查数据结构
                    if (!data.data || !Array.isArray(data.data)) {
                        throw new Error("返回的数据结构不正确，缺少data数组");
                    }
                    
                    // 处理任务数据，确保日期格式正确
                    console.log("原始任务数据:", data.data);
                    
                    // 创建一个新的任务数组，尝试不同的日期处理方式
                    const processedData = [];
                    
                    for (let i = 0; i < data.data.length; i++) {
                        const task = data.data[i];
                        const processedTask = {
                            id: task.id,
                            text: task.text,
                            duration: task.duration,
                            progress: task.progress,
                            parent: task.parent,
                            assignee: task.assignee,
                            status: task.status,
                            type: 'task'
                        };
                        
                        // 处理开始日期 - 确保日期格式为YYYY-MM-DD
                        if (task.start_date) {
                            // 尝试解析日期字符串
                            let dateStr = task.start_date;
                            
                            // 如果日期包含时间部分，只取日期部分
                            if (dateStr.includes(' ')) {
                                dateStr = dateStr.split(' ')[0];
                            }
                            
                            // 验证日期格式是否为YYYY-MM-DD
                            const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
                            if (dateRegex.test(dateStr)) {
                                processedTask.start_date = dateStr;
                                console.log(`任务 ${i} 开始日期: ${task.start_date} -> ${processedTask.start_date}, 持续时间: ${processedTask.duration}`);
                            } else {
                                console.error(`任务 ${i} 的日期格式不正确: ${dateStr}`);
                                // 尝试修复日期格式
                                const date = new Date(dateStr);
                                if (!isNaN(date.getTime())) {
                                    const year = date.getFullYear();
                                    const month = String(date.getMonth() + 1).padStart(2, '0');
                                    const day = String(date.getDate()).padStart(2, '0');
                                    processedTask.start_date = `${year}-${month}-${day}`;
                                    console.log(`修复后的日期: ${processedTask.start_date}`);
                                } else {
                                    console.error(`无法解析任务 ${i} 的日期: ${dateStr}`);
                                }
                            }
                        }
                        
                        processedData.push(processedTask);
                    }
                    
                    console.log("处理后的任务数据:", processedData);
                    
                    // 清空甘特图
                    gantt.clearAll();
                    
                    // 添加调试信息
                    console.log("甘特图配置:", {
                        date_format: gantt.config.date_format,
                        xml_date: gantt.config.xml_date,
                        scale_unit: gantt.config.scale_unit
                    });
                    
                    // 加载处理后的数据
                    gantt.parse({
                        data: processedData,
                        links: data.links || []
                    });
                    
                    // 强制重新渲染甘特图
                    gantt.render();
                    
                    // 使用showDate和adjustViewport方法确保甘特图正确显示所有任务
                    setTimeout(() => {
                        // 替代fitToContent方法，使用可用的方法调整视图
                        if (gantt.showTask && processedData.length > 0) {
                            // 显示第一个任务
                            gantt.showTask(processedData[0].id);
                        }
                        // 调整视图以显示所有任务
                        if (gantt.adjustViewport) {
                            gantt.adjustViewport();
                        }
                        console.log("调用adjustViewport方法替代fitToContent");
                        
                        // 如果有任务，显示第一个任务的日期
                        if (processedData.length > 0) {
                            const firstTask = processedData[0];
                            if (firstTask.start_date) {
                                const startDate = new Date(firstTask.start_date);
                                gantt.showDate(startDate);
                                console.log("显示第一个任务的开始日期:", startDate);
                            }
                        }
                    }, 500);
                    
                    // 检查甘特图渲染后的任务
                    setTimeout(() => {
                        const tasks = gantt.getTaskByTime();
                        console.log("甘特图渲染后的任务:", tasks);
                        if (tasks.length > 0) {
                            console.log("第一个任务的日期:", {
                                start_date: tasks[0].start_date,
                                end_date: tasks[0].end_date,
                                text: tasks[0].text,
                                duration: tasks[0].duration
                            });
                        }
                    }, 1000);
                    
                    console.log("甘特图数据加载完成");
                    
                    // 调整视图以显示所有任务
                    if (data.data.length > 0) {
                        // 显示当前日期
                        gantt.showDate(new Date());
                        
                        // 确保甘特图容器可以滚动
                        setTimeout(function() {
                            // 重新渲染甘特图以确保滚动条正确显示
                            gantt.render();
                            
                            // 确保网格区域的水平滚动条被隐藏
                            var gridHorScroll = document.querySelector('.gantt_grid .gantt_hor_scroll');
                            if (gridHorScroll) {
                                gridHorScroll.style.display = 'none';
                                gridHorScroll.style.height = '0';
                            }
                            
                            // 确保时间线区域显示水平滚动条
                            var timelineHorScroll = document.querySelector('.gantt_timeline .gantt_hor_scroll');
                            if (timelineHorScroll) {
                                timelineHorScroll.style.display = 'block';
                                timelineHorScroll.style.height = '15px';
                            }
                        }, 100);
                    } else {
                        console.log("项目没有任务数据");
                    }
                } catch (e) {
                    console.error("处理甘特图数据失败:", e);
                }
            })
            .catch(error => {
                console.error('Error loading project data:', error);
                
                // 移除加载状态
                var loadingElement = document.getElementById("gantt-loading");
                if (loadingElement) {
                    loadingElement.remove();
                }
            });
    }
    
    // 页面加载完成后初始化
    document.addEventListener("DOMContentLoaded", function() {
        console.log("DOM内容加载完成");
        
        // 初始化甘特图
        var initSuccess = initGantt();
        
        if (!initSuccess) {
            console.error("甘特图初始化失败");
            return;
        }
        
        // 检查是否选择了项目
        var selectedProjectId = "{{ selected_project.id if selected_project else '' }}";
        console.log("当前选择的项目ID:", selectedProjectId);
        
        if (selectedProjectId) {
            console.log("自动加载项目数据...");
            // 延迟加载数据，确保甘特图已初始化
            setTimeout(function() {
                loadProject();
            }, 200);
        }
    });
</script>
{% endblock %}

{% block content %}
<div class="container mx-auto">
    <!-- 面包屑导航 -->
    <nav class="text-sm breadcrumbs mb-6">
        <ol class="flex items-center space-x-2">
            <li><a href="{{ url_for('main.home') }}" class="text-gray-500 hover:text-gray-700">首页</a></li>
            <li><i class="fas fa-chevron-right text-gray-400 text-xs mx-2"></i></li>
            <li><a href="{{ url_for('project.list_projects') }}" class="text-gray-500 hover:text-gray-700">项目管理</a></li>
            <li><i class="fas fa-chevron-right text-gray-400 text-xs mx-2"></i></li>
            <li class="text-gray-700">甘特图</li>
        </ol>
    </nav>

    <!-- 项目选择 -->
    <div class="bg-white rounded-lg shadow mb-6 flex-shrink-0">
        <div class="p-4 border-b border-gray-200">
            <div class="flex flex-col md:flex-row md:items-center md:justify-between">
                <div class="flex items-center space-x-4 mb-4 md:mb-0">
                    <label class="text-sm font-medium text-gray-700" for="project_select">
                        选择项目
                    </label>
                    <select class="w-full md:w-64 border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent text-sm" id="project_select" onchange="loadProject()">
                        <option value="">-- 请选择项目 --</option>
                        {% for project in projects %}
                        <option value="{{ project.id }}" {% if selected_project and selected_project.id == project.id %}selected{% endif %}>{{ project.name }}</option>
                        {% endfor %}
                    </select>
                </div>
                {% if selected_project %}
                <div class="flex items-center space-x-2">
                    <a href="{{ url_for('project.project_detail', project_id=selected_project.id) }}" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-blue-600 transition">
                        <i class="fas fa-arrow-left mr-2"></i>返回项目详情
                    </a>
                </div>
                {% endif %}
            </div>
        </div>
        
        {% if selected_project %}
        <div class="p-4 border-b border-gray-200">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-blue-100 text-blue-500">
                    <i class="fas fa-project-diagram"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-500">当前项目</p>
                    <p class="text-xl font-semibold">{{ selected_project.name }}</p>
                    <p class="text-sm text-gray-600">{{ selected_project.description }}</p>
                </div>
            </div>
        </div>
        {% endif %}
    </div>
    
    <!-- 甘特图容器 -->
    <div class="bg-white rounded-lg shadow overflow-hidden flex-grow">
        <div id="gantt_here" class="gantt_container"></div>
        {% if not selected_project %}
        <div id="empty-state" class="text-center py-12">
            <p class="text-gray-500">请选择一个项目以查看甘特图</p>
        </div>
        {% endif %}
    </div>
</div>

{% endblock %}